﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //调拨
    public class ProductAllotController : Controller
    {
        private readonly IProductAllotService billServiceImpl = ServiceLocator.Instance.GetService<IProductAllotService>();	
        //
        // GET: /ProductAllot/

        public ActionResult Index()
        {
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = billServiceImpl.GetProductAllot(id);
            return View(billModel);
        }
        #endregion
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ProductAllotDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var aa = Add(roductInBillDto) as ContentResult;
            string actionResult = aa.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                roductInBillDto.Id = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {

                if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
                {
                    Audit(roductInBillDto.Id);//提交
                }
            }
            return Content("9");
        }
        #endregion
        #region 添加调拨
         [NoAuthorizated("Add")]
        public ActionResult Add(Guid?id)
        {
            ProductAllotDto billModel = null;

         
            if (id == null|| !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateAllotNextNO();

                var initSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ChengDuCode);//初始化默认组织机构和仓库
              //  var wareHouse = initSysData.Values.FirstOrDefault();
                var org = initSysData.Keys.FirstOrDefault();

                billModel = new ProductAllotDto { AllotNo = NO ,
                  AllotOrgName=org.Name,
                  AllotOrgID=org.Id
                };
             
            }
            else
            {
                Guid billId;
                Guid.TryParse(id.ToString(), out billId);
                billModel = this.billServiceImpl.GetProductAllot(billId);

            }
            ViewBag.TempId = Guid.Empty;


            return View(billModel);
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductAllotDto roductInBillDto)
        {
            #region 主数据处理
            var model = new ProductCheckBillModel();
            var uId = model.GetRequestFormValues(this.HttpContext, "AllotorName_val");
            if (!Guid.Empty.Equals(uId))
            {
                roductInBillDto.AllotorID = uId;
            }
            #endregion
            #region 明细行数据处理
            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProductAllotDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.ProductAllotID = checkId;
                if (item.Id == null || item.Id.Equals(Guid.Empty))
                {
                    item.Id = Guid.Empty;
                }
            });

            #endregion

            #region 数据验证
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
                return Content("-1");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    #region 验证
                    //验证
                    BLLQuery bq = new BLLQuery();
                    bool isValidate = true;
                    if (detailItems != null && detailItems.Count > 0)
                    {
                        foreach (var item in detailItems)
                        {
                            if (bq.ValidateOutOfLastSellOutNum(item.ProductSellBillDetailID, item.AllotAmount,false))
                            {
                                isValidate = false;
                                break;
                            }
                        }
                    }

                    if (!isValidate) { return Content("-3"); }//验证失败
                    #endregion
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        roductInBillDto.UpdateID = UserModel.GetLoginUserId(this.HttpContext);
                        roductInBillDto.UpdateDate = DateTime.Now;
                        this.billServiceImpl.UpdateProductAllot(roductInBillDto, detailItems);
                        return Content(roductInBillDto.Id.ToString());
                    }
                    else
                    {
                        roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                      var tempId=  this.billServiceImpl.AddProductAllot(roductInBillDto, detailItems);
                      return Content(tempId.ToString());
                    }
                }
                catch (Exception ex)
                {
                    return Content("-2");
                }
               
                ViewBag.PostState = 9;
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {

            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                billServiceImpl.ConvertProductAllotDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                billServiceImpl.ConvertProductAllotDeleteState(billId);
                return Content("9");
            }
        

            return Content("0");
        }
        #endregion
        #region 更新至库存
        public ActionResult UpdateToStock(Guid billId, string ids)
        {
            /*
            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                billServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            */
            return Content("0");
        }
        #endregion
        #region 获取调拨列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfAllots")]
        public ActionResult GetJsonOfAllots()
        {
            #region  EF的查询，效率低下，故暂时放弃不用
            /*
            int recordCount = 0;
            var productBills = billServiceImpl.GetProductAllots(out recordCount,1, 100);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u => { u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                         return u; 
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + recordCount + "\"}";
                return Content(target);
            }
            
            return Content("");
             */
            #endregion
            return Content(new BLLQuery().GetProductAllotBills(this.HttpContext));
        }
        /// <summary>
        /// 根据调拨ID，获得调拨所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //if (!billId.Equals(Guid.Empty))
            //{
            //    var billDetails = this.billServiceImpl.GetProductAllotDetails(billId);//.Where(p => p.Deleted == 0).ToList();
            //    if (billDetails != null && billDetails.Count() != 0)
            //    {
            //        var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
            //        var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //        target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
            //        return Content(target);
            //    }
            //}

            // return Content("");
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetProductAllotDetails(billId));

            }
            else
            {
                return Content("");
            }
            
            
           
            
        }
        #endregion
        #region 审核
        [NoAuthorizated("Audit")]
        public ActionResult Audit(Guid billId)
        {
            if (!billId.Equals(Guid.Empty))
            {
                var umodel = new UserModel();
                Guid uid = UserModel.GetLoginUserId(this.HttpContext);
                this.billServiceImpl.Audit(new List<Guid>() { billId }, uid, umodel.GetUserOrgID(uid));
                return Content("9");
            }
            return Content("0");
        }
        #endregion
      
    }
}
